import typescript from 'rollup-plugin-typescript2';
import { defineConfig } from 'rollup';
import { createFilter } from '@rollup/pluginutils';

// 自定义条件编译插件
function conditionalCompilation(options = {}) {
  const filter = createFilter(options.include, options.exclude);
  const platform = options.platform || 'H5';
  
  return {
    name: 'conditional-compilation',
    transform(code, id) {
      if (!filter(id)) return null;
      
      // 处理条件编译指令
      let transformedCode = code;
      
      // 移除不匹配平台的代码块
      const ifdefRegex = /\/\/ #ifdef ([^\n]+)([\s\S]*?)\/\/ #endif/g;
      transformedCode = transformedCode.replace(ifdefRegex, (match, condition, content) => {
        const conditions = condition.trim().split(/\s+/);
        if (conditions.includes(platform)) {
          return content;
        }
        return '';
      });
      
      // 处理 #ifndef 指令
      const ifndefRegex = /\/\/ #ifndef ([^\n]+)([\s\S]*?)\/\/ #endif/g;
      transformedCode = transformedCode.replace(ifndefRegex, (match, condition, content) => {
        const conditions = condition.trim().split(/\s+/);
        if (!conditions.includes(platform)) {
          return content;
        }
        return '';
      });
      
      return {
        code: transformedCode,
        map: null
      };
    }
  };
}

export default defineConfig({
  input: 'src/index.ts',
  output: [
    {
      file: 'dist/index.js',
      format: 'cjs',
      exports: 'named',
      sourcemap: true
    },
    {
      file: 'dist/index.esm.js',
      format: 'es',
      exports: 'named',
      sourcemap: true
    }
  ],
  plugins: [
    conditionalCompilation({
      platform: 'H5', // 默认构建为 H5 平台
      include: ['**/*.ts', '**/*.js']
    }),
    typescript({
      tsconfig: './tsconfig.json',
      clean: true,
      useTsconfigDeclarationDir: true
    })
  ],
  external: ['vue']
});